import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import { Button, Table, Input } from 'antd';
import Question from '../../../../../../components/Question';
import { cloneDeep } from 'lodash';

const CodeMap = forwardRef((props, ref) => {
  const { record } = props;
  const [data, setData] = useState([]);

  useEffect(() => {
    if (record.codeMap) {
      setData(cloneDeep(record.codeMap));
    } else {
      handleReset();
    }
  }, []);

  useImperativeHandle(ref, () => ({
    getData: () => data,
  }));

  // 添加
  const hanldAdd = () => {
    const tempData = [...data];
    const { thirdPath, innerPath } = record;
    const tempObj = {
      srcKey: thirdPath,
      destKey: innerPath,
    };
    tempData.push(tempObj);
    setData(tempData);
  };

  const handleChange = (value, index, key) => {
    const temp = [...data];
    if (key === 'srcCode') {
      const new_value = value.match(/[a-zA-Z0-9\u4e00-\u9fa5,]+/);
      temp[index][key] = new_value ? new_value[0] : '';
    } else {
      temp[index][key] = value;
    }
    setData(temp);
  };

  // 码值映射重置
  const handleReset = () => {
    const { thirdPath, innerPath } = record;
    const tempObj = {
      srcKey: thirdPath,
      destKey: innerPath,
    };
    setData([tempObj]);
  };

  const handleDelete = (index) => {
    const temp = [...data];
    temp.splice(index, 1);
    setData(temp);
  };

  const columns = [
    {
      title: '源key',
      dataIndex: 'srcKey',
    },
    {
      title: '码值',
      dataIndex: 'srcCode',
      filterIcon: <Question title='支持多码值,用逗号隔开' />,
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'srcCode')} />
      ),
    },
    {
      title: '映射key',
      dataIndex: 'destKey',
    },
    {
      title: '映射码值',
      dataIndex: 'destCode',
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'destCode')} />
      ),
    },
    {
      title: '描述',
      dataIndex: 'destDesc',
      render: (text, _, index) => (
        <Input value={text} onChange={(e) => handleChange(e.target.value, index, 'destDesc')} />
      ),
    },
    {
      title: '删除',
      dataIndex: 'action',
      render: (_, __, index) => (
        <Button type='text' onClick={() => handleDelete(index)}>
          删除
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Button onClick={hanldAdd}>增加</Button>
      <Table
        dataSource={data}
        columns={columns}
        rowKey={(_, index) => index}
        pagination={false}
        style={{ marginBottom: '20px' }}
      />
    </div>
  );
});
export default CodeMap;
